<?php
// $txt=file_get_contents('php://input');
// logfile($txt,'qunar_get_data');

if (!class_exists("go_sql")){
include("/var/www/html/new/conf/le.je");
  $le=new go_sql();
  $le->connect();
}

//初始化数据
$outSide = new SoapClient("http://open.12301.cc/openService/MXSE.wsdl",array('encoding' =>'UTF-8','cache_wsdl' => 0));
$ac='123492';
$pw='b4b55c7adcff5bdbc3d5a969e85cb8b2';

$ac1='16ucom';
$pw1='c33367701511b4f6020ec61ded352059';
$inSide = new SoapClient(null,array("location" => "http://localhost/open/openService/pft_insideMX.php","uri" => "www.16u.com?ac_16u=$ac1|pw_16u=$pw1|auth_16u=true"));
 
$txt ='method=getProductByQunar&requestParam=%7B%22data%22%3A%22PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9InllcyI%2FPjxyZXF1ZXN0IHhtbG5zPSJodHRwOi8vcGlhby5xdW5hci5jb20vMjAxMy9RTWVucGlhb1JlcXVlc3RTY2hlbWEiPjxoZWFkZXI%2BPGFwcGxpY2F0aW9uPlF1bmFyLk1lbnBpYW8uQWdlbnQ8L2FwcGxpY2F0aW9uPjxwcm9jZXNzb3I%2BU3VwcGxpZXJEYXRhRXhjaGFuZ2VQcm9jZXNzb3I8L3Byb2Nlc3Nvcj48dmVyc2lvbj52Mi4wLjA8L3ZlcnNpb24%2BPGJvZHlUeXBlPkdldFByb2R1Y3RCeVF1bmFyUmVxdWVzdEJvZHk8L2JvZHlUeXBlPjxjcmVhdGVVc2VyPlF1bmFyLk1lbnBpYW8uQWdlbnQ8L2NyZWF0ZVVzZXI%2BPGNyZWF0ZVRpbWU%2BMjAxNS0wOS0xNiAxNjozNTowMzwvY3JlYXRlVGltZT48c3VwcGxpZXJJZGVudGl0eT5KWE1ZU1RNV1E8L3N1cHBsaWVySWRlbnRpdHk%2BPC9oZWFkZXI%2BPGJvZHkgeHNpOnR5cGU9IkdldFByb2R1Y3RCeVF1bmFyUmVxdWVzdEJvZHkiIHhtbG5zOnhzaT0iaHR0cDovL3d3dy53My5vcmcvMjAwMS9YTUxTY2hlbWEtaW5zdGFuY2UiPjxtZXRob2Q%2BQUxMPC9tZXRob2Q%2BPGN1cnJlbnRQYWdlPjE8L2N1cnJlbnRQYWdlPjxwYWdlU2l6ZT4yMDwvcGFnZVNpemU%2BPHJlc291cmNlSWQ%2BPC9yZXNvdXJjZUlkPjwvYm9keT48L3JlcXVlc3Q%2B%22%2C%22securityType%22%3A%22MD5%22%2C%22signed%22%3A%224C38C6B37F8B17F350540413CED999B5%22%7D';

$arr=array();	
parse_str($txt,$arr);

$rt=$arr['requestParam'];
$c = AnalyticalXml($rt);  //解析xml
$supplierIdentity=$c->header->supplierIdentity; 
$signkey = QueryKey($supplierIdentity); //获取密钥

if ($arr['method']=='createOrderForAfterPaySync') {//下单
		
	$tids = (string)$c->body->orderInfo->product->resourceId;
	$a_tids = explode('_',$tids);
	$tid = $a_tids[0]; //门票id
	$aid = $a_tids[1]; //供应商id
	$Venue=$a_tids[2];
	$in13 = "";
	if($Venue){
		$Partition = $a_tids[3];
		$Screenings = $a_tids[4];
		$in13 = json_encode(array($Venue,$Partition,$Screenings));
	}
	
	$remotenum = (string)$c->body->orderInfo->orderId;
	$tprice = (string)$c->body->orderInfo->product->sellPrice;
	$tnum = (int)$c->body->orderInfo->orderQuantity;
	$playtime = (string)$c->body->orderInfo->product->visitDate;
	$ordername = (string)$c->body->orderInfo->contactPerson->name;
	$ordertel= (string)$c->body->orderInfo->contactPerson->mobile;
	$IDkard  = (string)$c->body->orderInfo->visitPerson->person->credentials;
	
	$str="select landid from uu_jq_ticket where id='$tid' limit 1";	
	$GLOBALS['le']->query($str);
	$GLOBALS['le']->fetch_assoc();
	$lid=$GLOBALS['le']->f('landid');		
		
	$arr_data=array("ac"=>$ac,"pw"=>$pw,"in0"=>$lid,"in1"=>$tid,"in2"=>$remotenum,"in3"=>$tprice,"in4"=>$tnum,"in5"=>$playtime,"in6"=>$ordername,"in7"=>$ordertel,"in8"=>"","in9"=>0,"in10"=>2,"in11"=>0,"in12"=>"","in13"=>$in13,"in14"=>0,"in15"=>0,"in16"=>$aid,"in17"=>$IDkard); 

	$code="";
	$ordern="";
	$describe="";
	$cxml=$outSide->__soapCall("PFT_Order_Submit",$arr_data);
	$cx=simpleXML_load_string($cxml);
	if ($cx->Rec->UUerrorcode){//下单失败
		if((int)$cx->Rec->UUerrorcode==122){
			//授信不足，提醒供应商给分销商授信
			$str="select mobile from pft_member where id='$aid' limit 1";	
			$GLOBALS['le']->query($str);
			$GLOBALS['le']->fetch_assoc();
			$aid_Tel=$GLOBALS['le']->f('mobile');
			$inSide->Send_SMS_V($aid_Tel,'系统公告:您授信给分销商[去哪儿]的授信余额不足，请尽快补充授信，避免影响销量');
		}
		$txt_json=json_encode($arr_data);		
		$orderStatus='PREPAY_ORDER_PRINT_FAILED';
		$code=Err_Code((int)$cx->Rec->UUerrorcode);
		$describe=Err_Word((int)$cx->Rec->UUerrorcode);
		logfile($txt_json.'|'.$cx->Rec->UUerrorcode,'submitO_fail');
	}else{//下单成功		
		$ordern=(string)$cx->Rec->UUordernum;		
		$str="insert into pft_coop_qunar_record (orderid,dtype) values ('$ordern',9)";
		$GLOBALS['le']->query($str);		
		$code=1000;
		$orderStatus='PREPAY_ORDER_PRINT_SUCCESS';
		$describe='成功';		
		logfile($ordern.'|'.$remotenum,'submitO_success');		
	}	
	$nowdate = date('Y-m-d H:i:s');
	$xml=<<<XML
<?xml version="1.0" encoding="UTF-8"?>
<!--Sample XML file generated by XMLSpy v2013 (http://www.altova.com)-->
<response xsi:schemaLocation="http://piao.qunar.com/2013/QMenpiaoResponseSchema QMResponseDataSchema-2.0.1.xsd" xmlns="http://piao.qunar.com/2013/QMenpiaoResponseSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<header>
		<application>Qunar.Menpiao.Agent</application>
		<processor>SupplierDataExchangeProcessor</processor>
		<version>v2.0.1</version>
		<bodyType>CreateOrderForAfterPaySyncResponseBody</bodyType>
		<createUser>$supplierIdentity</createUser>
		<createTime>$nowdate</createTime>
		<code>$code</code>
		<describe>$describe</describe>
	</header>
	<body xsi:type="CreateOrderForAfterPaySyncResponseBody">
		<orderInfo>
			<partnerorderId>$ordern</partnerorderId>
			<orderStatus>$orderStatus</orderStatus>
		</orderInfo>
	</body>
</response>
XML;
	$response = responseSign($xml,$signkey);
	echo $response;
}
elseif ($arr['method']=='noticeOrderRefundedByQunar'){//撤改
	
	$ordern = (string)$c->body->orderInfo->partnerorderId;
	$tnum = (int)$c->body->orderInfo->orderQuantity;
	$rnum = (int)$c->body->orderInfo->refundQuantity;
	$refundSeq = (string)$c->body->orderInfo->refundSeq;
	$noticeCanBeIgnored = (string)$c->body->orderInfo->noticeCanBeIgnored;
	
	//查询是否有修改记录
	$str="select refundSeq,tnum from pft_coop_qunar_record where orderid='$ordern' and status=0 and dtype=0 order by id desc limit 1";	
	$GLOBALS['le']->query($str);
	$GLOBALS['le']->fetch_assoc();
	$refundSeq_r=$GLOBALS['le']->f('refundSeq');
	$tnum_r=$GLOBALS['le']->f('tnum');
	$tnum=($tnum_r)?$tnum_r:$tnum;
	
	$rnum=($rnum==0)?$tnum:$rnum;
	$num=$tnum-$rnum;
	
	if ($refundSeq!=$refundSeq_r && ($noticeCanBeIgnored == 'false' || $noticeCanBeIgnored == '')){ 	
		$arr_data=array("ac"=>$ac,"pw"=>$pw,"in0"=>$ordern,"in1"=>$num,"in2"=>""); 
		$cxml=$outSide->__soapCall("Order_Change_Pro",$arr_data);
		$cx=simpleXML_load_string($cxml);
		if ($cx->Rec->UUerrorcode){//撤改失败
			$txt_json=json_encode($arr_data);
			$code=Err_Code((int)$cx->Rec->UUerrorcode);
			$describe=Err_Word((int)$cx->Rec->UUerrorcode);
			logfile($ordern.'|'.(int)$cx->Rec->UUerrorcode,'modifyO_fail');		
		}else{ //成功
			$code=1000;
			$describe='成功';
			//修改成功记录
			$str="insert pft_coop_qunar_record set orderid='$ordern',refundSeq='$refundSeq',tnum=$num,rnum=$rnum";
			$GLOBALS['le']->query($str);
			logfile($ordern.'|100','modifyO_success');	
		}	
		$nowdate = date('Y-m-d H:i:s');
		$xml=<<<XML
<?xml version="1.0" encoding="UTF-8"?>
<response xsi:schemaLocation="http://piao.qunar.com/2013/QMenpiaoResponseSchema QMResponseDataSchema-2.0.1.xsd" xmlns="http://piao.qunar.com/2013/QMenpiaoResponseSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<header>
		<application>Qunar.Menpiao.Agent</application>
		<processor>SupplierDataExchangeProcessor</processor>
		<version>v2.0.1</version>
		<bodyType>NoticeOrderRefundedByQunarResponseBody</bodyType>
		<createUser>$supplierIdentity</createUser>
		<createTime>$nowdate</createTime>
		<code>$code</code>
		<describe>$describe</describe>
	</header>
	<body xsi:type="NoticeOrderRefundedByQunarResponseBody">
		<message></message>
	</body>
</response>
XML;
		$response = responseSign($xml,$signkey);
		echo $response;
	}
}
elseif ($arr['method']=='sendOrderEticket'){ //重发码接口   
    $ordern=(string)$c->body->orderInfo->partnerOrderId;
    $resend_array = array("ac"=>$ac,"pw"=>$pw,"in0"=>$ordern);
	$resend_sms = $outSide->__soapCall("reSend_SMS_Global_PL",$resend_array);
	$resend_xml= simplexml_load_string($resend_sms);
	if ($resend_xml->Rec->UUerrorcode){
		$txt_json=json_encode($resend_array);	
		$code=Err_Code((int)$resend_xml->Rec->UUerrorcode);
		$describe=Err_Word((int)$resend_xml->Rec->UUerrorcode);
		logfile($resend_array.'|'.(int)$resend_xml->Rec->UUerrorcode,'resendO_fail');
	}else{
	//成功
		$code=1000;
		$describe='成功';
		logfile($resend_array.'|100','resendO_success');
	}   
	$nowdate = date('Y-m-d H:i:s');    
	$xml=<<<XML
<?xml version="1.0" encoding="UTF-8"?>
<response xsi:schemaLocation="http://piao.qunar.com/2013/QMenpiaoResponseSchema QMResponseDataSchema-2.0.1.xsd" xmlns="http://piao.qunar.com/2013/QMenpiaoResponseSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<header>
		<application>Qunar.Menpiao.Agent</application>
		<processor>SupplierDataExchangeProcessor</processor>
		<version>v2.0.1</version>
		<bodyType>SendOrderEticketResponseBody</bodyType>
		<createUser>$supplierIdentity</createUser>
		<createTime>$nowdate</createTime>
		<code>$code</code>
		<describe>$describe</describe>
	</header>
	<body xsi:type="SendOrderEticketResponseBody">
		<message></message>
	</body>
</response>
XML;
	$response = responseSign($xml,$signkey);
	echo $response;
}
elseif ($arr['method']=='applyOrderRefundByUser'){//【订单】用户向供应商申请退款

	$ordern=(string)$c->body->orderInfo->partnerorderId;
	$tnum=(int)$c->body->orderInfo->orderQuantity;
	$rnum=(int)$c->body->orderInfo->refundQuantity;
	$refundSeq=(string)$c->body->orderInfo->refundSeq;
	
	//查询是否有修改记录
	$str="select refundSeq,tnum from pft_coop_qunar_record where orderid='$ordern' and status=0 and dtype=0 order by id desc limit 1";	
	$GLOBALS['le']->query($str);
	$GLOBALS['le']->fetch_assoc();
	$refundSeq_r=$GLOBALS['le']->f('refundSeq');
	$tnum_r=$GLOBALS['le']->f('tnum');
	$tnum=($tnum_r)?$tnum_r:$tnum;
	
	$rnum=($rnum==0)?$tnum:$rnum;
	$num=$tnum-$rnum;
	
	if ($refundSeq!=$refundSeq_r){
		$arr_data=array("ac"=>$ac,"pw"=>$pw,"in0"=>$ordern,"in1"=>$num,"in2"=>"");
		$cxml=$outSide->__soapCall("Order_Change_Pro",$arr_data);
		$cx=simpleXML_load_string($cxml);
		if ((int)$cx->Rec->UUerrorcode){
			$applyOrder= 'REJECT';
			$txt_json=json_encode($arr_data);	
			$code=Err_Code((int)$cx->Rec->UUerrorcode);
			$describe=Err_Word((int)$cx->Rec->UUerrorcode);
			logfile($txt_json.'|'.(int)$cx->Rec->UUerrorcode,'UmodifyO_fail');
		}else{		//成功
			$code=1000;
			$describe='成功';
			//修改成功记录
			$applyOrder = 'APPROVE';
			$str="insert pft_coop_qunar_record set orderid='$ordern',refundSeq='$refundSeq',tnum=$num,rnum=$rnum";
			$GLOBALS['le']->query($str);
			logfile($ordern.'|100','UmodifyO_success');
		}
		$nowdate = date('Y-m-d H:i:s');
		$xml=<<<XML
<?xml version="1.0" encoding="UTF-8"?>
<response xsi:schemaLocation="http://piao.qunar.com/2013/QMenpiaoResponseSchema QMResponseDataSchema-2.0.1.xsd" xmlns="http://piao.qunar.com/2013/QMenpiaoResponseSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<header>
		<application>Qunar.Menpiao.Agent</application>
		<processor>SupplierDataExchangeProcessor</processor>
		<version>v2.0.1</version>
		<bodyType>ApplyOrderRefundByUserResponseBody</bodyType>
		<createUser>$supplierIdentity</createUser>
		<createTime>$nowdate</createTime>
		<code>$code</code>
		<describe>$describe</describe>
	</header>
	<body xsi:type="ApplyOrderRefundByUserResponseBody">
		<message></message>
	</body>
</response>
XML;
		$response = responseSign($xml,$signkey);
		echo $response;
		
		$applyOrder_array = array( //退款后需要通知去哪儿
			'applyOrder'=>$applyOrder,
			'supplierIdentity'=>(string)$supplierIdentity,
			'nowdate'=>$nowdate,
			'ordern'=>$ordern,
			'refundSeq'=>(string)$refundSeq,
			'tnum'=>$tnum,
			'rnum'=>(int)$rnum,
			'signkey'=>$signkey
		);
		$approve = User_refund_notice_qunar($applyOrder_array);
	}
}
elseif ($arr['method']=='getProductByQunar'){// 获取产品信息
	$sql="select cooperation_way from uu_qunar_use where DockingMode=0 and supplierIdentity='$supplierIdentity' limit 1";
	$GLOBALS['le']->query($sql); 
	$GLOBALS['le']->fetch_assoc();
	$cooperation_way = $GLOBALS['le']->f('cooperation_way');
	$method = (string)$c->body->method; //方法
	// echo $method;exit;
	$count = 0;	
	if($method == 'SINGLE'){//获取单个产品信息
		$count = 1;
		$data_array = array();		
		$data_array = Get_Product_data((string)$c->body->resourceId,$inSide,$outSide,$ac,$pw,$count,$cooperation_way);
		$string = Get_Product_Body_XML($data_array);
		$string_header = Get_Product_XML($string,$count);
		$js_sing= responseSign($string_header,$signkey);
		echo $js_sing;
	}
	elseif($method == 'ALL'){//获取全部产品信息
		//获取场次产品信息
		$currentPage =(int)$c->body->currentPage;// 当前页数
		$pageSize =(int)$c->body->pageSize; //每页记录数
		$begin = ($currentPage-1)*$pageSize;//计算分页数
		$count_select = "select count(id) as count from uu_qunar_use where supplierIdentity='$supplierIdentity'  and coop_id=0 and DockingMode=0";
		$GLOBALS['le']->query($count_select); 
		$GLOBALS['le']->fetch_assoc();
		$count = $GLOBALS['le']->f('count'); //获取总数
		$search = "select tid_aid from uu_qunar_use where supplierIdentity='$supplierIdentity' and  coop_id=0 and DockingMode=0 limit $begin ,$pageSize";
		$GLOBALS['le']->query($search);	
		$data = array();
		while($row=$GLOBALS['le']->fetch_assoc()){ 
			$data[] = $row;
		}
		if(isset($_REQUEST['screen']) && $_REQUEST['screen'] == 1){
			include '../round_ticket.php';
			foreach($data as $row){
				$screenproducts []= get_show_Data($row['tid_aid'],$inSide);
				// print_r($screenproducts);exit;
				$string .= $screenproducts[0]['data'];
				$count  += $screenproducts[0]['cnt'];
			}			
		}
		else{		
			foreach($data as $row){
				$data_array = array();
				$data_array = Get_Product_data($row['tid_aid'],$inSide,$outSide,$ac,$pw,$count,$cooperation_way);	
				$string.= Get_Product_Body_XML($data_array);	
			}
		}
		// print_r($string);exit;
		$string_header = Get_Product_XML($string,$count);
		$js_sing= responseSign($string_header,$signkey);
		echo $js_sing;
	}
}
elseif($arr['method']=='checkCreateOrderForAfterPaySync'){ //校验订单
	$tids = (string)$c->body->orderInfo->product->resourceId;//产品id
	$orderQuantity = (string)$c->body->orderInfo->orderQuantity;//订单数量
	$visitDate=(string)$c->body->orderInfo->product->visitDate;//游玩日期
	$a_tids = explode('_',$tids);
	$tid = $a_tids[0]; //门票id
	$aid = $a_tids[1]; //供应商id
	$fid = 2175;
    if(!$tid)  {
        $code = 90001;
        $describe = '请求数据有误';
        $re_xml  = checkAfter($code,$describe,$supplierIdentity,$signkey);
        echo $re_xml;
        exit;
    }
    //获取票信息
    $sql= "select pid from uu_jq_ticket where id=".$tid." limit 1 ";
    $GLOBALS['le']->query($sql);
    if(!($pid =$GLOBALS['le']->fetch_assoc())){
        $code = 90001;
        $describe = '产品信息出错';
        $re_xml  = checkAfter($code,$describe,$supplierIdentity,$signkey);
        echo $re_xml;
        exit;
    }else {
        $pid = $GLOBALS['le']->f('pid');
    }

    // 获取产品数据
    $str="select p.id as pid,p.apply_limit,p.salerid,p.p_status,p.apply_did,l.id as lid,l.title as ltitle,l.p_type,t.id as tid,t.tprice,t.pay,t.title as ttitle,t.delaydays,t.ddays,t.buy_limit_low,t.buy_limit_up,t.status,t.storage_open,t.order_start,t.order_end,t.storage,t.getaddr,f.dhour,f.series_model,f.mdays,f.v_ID_support,t.sourceT from uu_products p left join uu_jq_ticket t on p.id=t.pid left join uu_land l on p.contact_id=l.id left join uu_land_f f on p.id=f.pid where p.id=$pid limit 1";
    $GLOBALS['le']->query($str);
    $p_info=$GLOBALS['le']->fetch_assoc();

    // 是否在售
    if($p_info['apply_limit']!=1){
        $code = 90001;
        $describe = '门票不在售';
        $re_xml  = checkAfter($code,$describe,$supplierIdentity,$signkey);
        echo $re_xml;
        exit;
    }
    // 是否有购买权限
    $auth = autoCheck($fid,$aid,$p_info);
    if(!$auth['auth']){
        $code = 90001;
        $describe = '没有购买权限';
        $re_xml  = checkAfter($code,$describe,$supplierIdentity,$signkey);
        echo $re_xml;
        exit;
    }

    // 检测套票子票
    if($p_info['p_type']=='F'){
        $chkResult = \pft\Prod\Sale::PackageTicketCheck($inSide, $pid, $fid, $aid, substr($valid_start,0,10), $num);
        if($chkResult['code']!=200){

            $code = 90001;
            $describe = '请求数据有误';
            $re_xml  = checkAfter($code,$describe,$supplierIdentity,$signkey);
            echo $re_xml;
            exit;
        }
    }

    // 价格获取
    $begintime = $visitDate.' 23:59:59';//游玩日期;
    $tnum = $orderQuantity;
    // 如果是时间段，判断预定日是否在有效期内
    if($p_info['p_type']!='F' && $p_info['order_start']!='' && $p_info['order_end']!=''){
        if(!($begintime<$p_info['order_end']&&$begintime>$p_info['order_start'])){
            $code = 90001;
            $describe = '购买日期门票失效';
            $re_xml  = checkAfter($code,$describe,$supplierIdentity,$signkey);
            echo $re_xml;
            exit;
        }
    }
    $sql = "select account,dname from pft_member where id=".$fid." limit 1";
    $GLOBALS['le']->query($sql);
    $d_info=$GLOBALS['le']->fetch_assoc();
    $xml = $inSide->Dynamic_Price_And_Storage($ac,$pid,$visitDate,1,0,1,$aid);
    if($xml==105 || $xml==1065){
        $code = 90001;
        $describe = '库存不足';
        $re_xml  = checkAfter($code,$describe,$supplierIdentity,$signkey);
        echo $re_xml;
        exit;
    }

    $obj = simplexml_load_string($xml);
    // 库存判断
    $storage = $obj->Rec->UUstorage;
    if($storage>-1){
        $storagexml = $inSide->Dynamic_Storage_Check($p_info['tid'], 1, substr($begintime,0,10));
        $storagexml = simplexml_load_string($storagexml);
        $dayStorage = explode("|", (string)$storagexml->Rec->UUXstr);
        $useStorage = $dayStorage[1];// 已使用库存
        $surplus    = $storage - $useStorage;// 剩余库存
        if($surplus<$tnum){
            $code = 90001;
            $describe = '库存不足';
            $re_xml  = checkAfter($code,$describe,$supplierIdentity,$signkey);
            echo $re_xml;
            exit;
        }
    }

    // 订单金额
    $tprice = (string)$obj->Rec->UUsprice;
    $totalMoney = $tprice*$tnum;
    // 初始自供自销
    $fundXml= $inSide->PFT_Member_Fund($fid,1,$aid);
    $fundXml1=simplexml_load_string($fundXml);
    $fundXml=$inSide->PFT_Member_Fund($fid,2,$aid);
    $fundXml2=simplexml_load_string($fundXml);
    $canUseMoney = (string)$fundXml1->Rec->UUkmoney + (string)$fundXml2->Rec->UUbasecredit;

    if(($canUseMoney)<$totalMoney){
        $code = 90001;
        $describe = '余额不足';
        $re_xml  = checkAfter($code,$describe,$supplierIdentity,$signkey);
        echo $re_xml;
        exit;
    }else{
        $code = 1000;
        $describe = '成功';
        $re_xml  = checkAfter($code,$describe,$supplierIdentity,$signkey);
        echo $re_xml;
        exit;
    }

}
elseif ($arr['method']=='testAlive'){//心跳检测
	echo 'alive';
}



//以下是函数部分

//校验供应链
function  autoCheck($fid,$aid,$p_info){
    $arr = array('self'=>false,'auth'=>false);
    $pid = $p_info['pid'];
    if($p_info['apply_did']==$fid){ // 自供应
        $arr['self'] = true;
        $arr['auth'] = true;
        return $arr;
    }
    if($p_info['apply_did']==$aid){ // 直接供应
        $sql="select pids from `pft_product_sale_list` where fid=$fid and aid=$aid LIMIT 1";
        $GLOBALS['le']->query($sql);
        $GLOBALS['le']->fetch_assoc();
        $pids=$GLOBALS['le']->f("pids");
        if($pids=='A') $arr['auth'] = true;
        if(in_array($pid,explode(",",$pids)))$arr['auth'] = true;
        return $arr;
    }
    // 多手供应
    $sql="select * from pft_p_apply_evolute where pid=$pid and sid=$aid and fid=$fid and status=0 limit 1";
    $GLOBALS['le']->query($sql);
    if($row=$GLOBALS['le']->fetch_assoc())$arr['auth'] = true;
    return $arr;
}
//校验订单提交参数
function checkAfter($code,$describe,$supplierIdentity,$signkey){

    $nowdate=date("Y-m-d H:i:s");
    $xml=<<<XML
<?xml version="1.0" encoding="UTF-8"?>
<response xsi:schemaLocation="http://piao.qunar.com/2013/QMenpiaoResponseSchema QMResponseDataSchema-2.0.1.xsd" xmlns="http://piao.qunar.com/2013/QMenpiaoResponseSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<header>
		<application>Qunar.Menpiao.Agent</application>
		<processor>SupplierDataExchangeProcessor</processor>
		<version>v2.0.1</version>
		<bodyType>CheckCreateOrderForAfterPaySyncResponseBody</bodyType>
		<createUser>{$supplierIdentity}</createUser>
		<createTime>{$nowdate}</createTime>
		<code>{$code}</code>
		<describe>{$describe}</describe>
	</header>
	<body xsi:type="CheckCreateOrderForAfterPaySyncResponseBody">
		<message></message>
	</body>
</response>
XML;
	// print_r($xml);exit;
    $response = responseSign($xml,$signkey);
    echo $response;
}

//解析xml
function AnalyticalXml($rt){
	$arr1=json_decode($rt);
	$xml=base64_decode($arr1->data);
	$c=simpleXML_load_string($xml);
	return $c;
}

//获取密钥
function QueryKey($supplierIdentity){
	$sql="select signkey from uu_qunar_use where DockingMode=0 and supplierIdentity='$supplierIdentity' limit 1";
	$GLOBALS['le']->query($sql); 
	$GLOBALS['le']->fetch_assoc();
	$signkey = $GLOBALS['le']->f('signkey');
	return $signkey;
}

//加密
function responseSign($string,$signkey){
	$bstr=base64_encode($string);
	$signed=strtoupper(md5($signkey.$bstr));
	$arr=array('data'=>$bstr,'signed'=>$signed,'securityType'=>'MD5');	
	return json_encode($arr);
}

//日志记录
function logfile($txt,$logname){
	$fp = fopen('/var/www/html/coop/callback/logs/'.date('Y-m-d').$logname.'.txt',"a");
	flock($fp, LOCK_EX);
	fwrite($fp,date('Y-m-d H:i:s')."|".$txt."\n");
	flock($fp, LOCK_UN);
	fclose($fp);
}

//错误代码
function Err_Code($errcode){
	$arr_X_code=array(101=>20027,103=>20011,105=>12001,107=>90005,112=>20006,115=>90007,116=>14007,119=>13009,123=>13001,130=>20005,131=>20006,133=>14009,134=>14010,1061=>20004,1062=>20022,1065=>13007,1071=>20010,1072=>20007,1075=>13004,1077=>13005);
	$ecode=@$arr_X_code[$errcode];
	if (!$ecode) $ecode=90001;
	return $ecode;
}
//错误描述
function Err_Word($errcode){
	$arr_X_word=array(
		103=>'您选择的出行日期格式不合法',
		101=>'创建订单异常，用户未登陆',
		105=>'产品不存在，不可预订',
		107=>'供应商交互XML解析错误',
		112=>'创建订单异常，取票人手机号码异常',
		115=>'web服务调用错误',
		116=>'电子票最多重复发送5次',
		119=>'订单状态不正确，不能重新发送入园凭证',
		122=>'资金账户余额不足',
		123=>'订单不存在',
		130=>'创建订单异常，取票人邮箱格式不合法',
		131=>'创建订单异常，取票人手机号码异常',
		133=>'订单消费失败，订单还未到有效使用日期',
		134=>'订单消费失败，订单已超过有效使用日期',
		1061=>'创建订单异常，选购产品不存在',
		1062=>'创建订单异常，库存不足',
		1063=>'总库存已售罄',		
		1065=>'订单产品价格信息异常',
		1066=>'商品票类数据出错',
		1067=>'商品数据出错',
		1068=>'商品需提前预定',
		1069=>'已超过当日购买的时间',
		1071=>'创建订单异常，出行日期为空',
		1072=>'创建订单异常，取票人姓名异常',
		1075=>'订单存在，但不属于该用户',
		1077=>'该订单无法修改',
	);
	$eword=@$arr_X_word[$errcode];
	if (!$eword) $eword='其他错误';
	return $eword;
}

//获取产品信息
function Get_Product_data($tids,$inSide,$outSide,$ac,$pw,$count,$cooperation_way){ // 这里是获取产品信息数据
		$a_tids=explode('_',$tids);
		$tid=$a_tids[0]; //门票id
		$aid = $a_tids[1]; //供应商id
			
		$str="select a.id as lid,a.title as ltitle,a.jqts,b.title as ttitle ,a.address,a.delaytime,b.pay,b.buy_limit_up,b.buy_limit_low,b.order_end,b.order_start,b.delaytype,b.delaydays,b.notes,b.tprice,b.ddays,b.pid,b.getaddr,b.cancel_auto_onMin,d.dhour from uu_land a inner join uu_jq_ticket b on (a.id = b.landid) left join uu_products c on(b.pid = c.id) left join uu_land_f d on(b.id = d.tid) where b.id='$tid' and c.apply_limit = 1 and c.p_status = 0 limit 1";		
	    $GLOBALS['le']->query($str);
		$GLOBALS['le']->fetch_assoc();		
		
		$resourceId 		= $tids; 								//去哪儿供应商产品id
		$sightName 			= $GLOBALS['le']->f('ltitle'); 			//景区名称
		$city 				= $GLOBALS['le']->f('address'); 		//目的地
		$sightAddress 		= $GLOBALS['le']->f('address'); 		//景区地址
		$productName 		= $GLOBALS['le']->f('ttitle'); 			//产品名称
		$pay 				= $GLOBALS['le']->f('pay'); 			//支付方式
		$marketPrice 		= $GLOBALS['le']->f('tprice')* 100;  	//门市价
		$remind 			= $GLOBALS['le']->f('jqts'); 			//使用说明
		$feeInfo 			= $GLOBALS['le']->f('notes');  			//费用说明			
		$smsTemplet 		= $GLOBALS['le']->f('getaddr');			//取票信息
		$order_end 			= strtotime($GLOBALS['le']->f('order_end'));
		$order_start 		= strtotime($GLOBALS['le']->f('order_start'));
		$ddays 				= $GLOBALS['le']->f('ddays');
		$bookAdvanceDay 	= ( $ddays== 0 ) ? '' : $ddays;  //提前预订的天数
		$bookAdvanceTime 	= $GLOBALS['le']->f('dhour');  			//提前预定时间
		$bookAdvanceTime 	= date('H:i',strtotime($bookAdvanceTime));
		$autoCancelTime 	= $GLOBALS['le']->f('cancel_auto_onMin');//不支付自动取消订单时间
		$useAdvanceHours 	= explode('|',$GLOBALS['le']->f('delaytime')); //延迟验证时间
		$useAdvanceHour 	= $useAdvanceHours[0] == 0 ? '' : $useAdvanceHours[0] ; //延迟验证时间（取小时）	
	    $nameRequired 		= 'TRUE' ; 								//需要取票人姓名
		$visitPersonRequiredForQuantity = '999'; 					//每几个游客共享一个游客信息
		$refundInfo 		= '未使用可申请退款';   				//默认
		$pid				= $GLOBALS['le']->f('pid'); 			//产品id
		$minimum =  $GLOBALS['le']->f('buy_limit_low');  //最少购买票数
		// $maximum =  $GLOBALS['le']->f('buy_limit_up');  //最多购买票数	
		
		if($pay == 1){ //支付方式 PREPAY在线支付 CASHPAY景区支付
			$paymentType = 'PREPAY';
		}elseif($pay == 0){ 
			$paymentType ='CASHPAY'; 
		}
		
		$delaydays = $GLOBALS['le']->f('delaydays'); //允许推迟游玩的天数
		$delaytype = $GLOBALS['le']->f('delaytype'); //允许推迟的天数使用0游玩时间/1下单时间
		if($delaydays!=0){
			if($delaytype==0){ //游玩日期起有效
				$validType='BETWEEN_USE_DATE_AND_N_DAYSAFTER';
				$daysAfterUseDateValid = $delaydays;
				if($delaydays==0) $daysAfterUseDateValid = 1;
			}elseif($delaytype==1){ //下单日期起有效
				$validType = 'BETWEEN_BOOK_DATE_AND_N_DAYSAFTER';
				$daysAfterBookDateValid = $delaydays;
			}
			$searchday =$delaydays;		
		}elseif($delaydays==0 && $order_start){//截止时间有效	
			$validType ='BETWEEN_USE_DATE_AND_N_DAYSAFTER';
			$searchday = ceil(($order_end-$order_start)/86400);
			$daysAfterUseDateValid = $searchday;
		}else{
			$validType = 'USE_DATE';	// 当天有效
			$daysAfterUseDateValid = 1;
			$searchday = 90;
		}			
		$calendarPrices = ''; //日历价格
		$periodPrices = '';  //期票价格
		if( $validType=='BETWEEN_USE_DATE_AND_N_DAYSAFTER'){ //期票模式		
			$date = date('Y-m-d',$order_start);
			$getprice = $inSide->Dynamic_Price_And_Storage($ac,$pid,$date,1,1,1,$aid);
			if($getprice != 105 && $getprice !=1065 && $getprice !=103){
				$getpricexml =  simplexml_load_string($getprice);
				// print_r($getpricexml);exit;
				$lprice = (int)$getpricexml->Rec->UUsprice;  //零售价
				$sellstock = ((int)$getpricexml->Rec->UUstorage == -1) ? '9999':(string)$getpricexml->Rec->UUstorage; //库存	
				$maximum = $sellstock;
				if($cooperation_way == 0){   //佣金模式,获取建议零售价, 只需要传sellPrice
					$sellPrice = $lprice;  //售票价
				}elseif($cooperation_way == 1){ //底价模式，获取结算价
					$date = date('Y-m-d',$order_start);
					$getprice = $inSide->Dynamic_Price_And_Storage($ac,$pid,$date,1,0,1,$aid);
					$getpricexml =  simplexml_load_string($getprice);
					$jsprice = (int)$getpricexml->Rec->UUsprice;  //结算价
					$sellPrice = $lprice;  //售票价
					$settlePrice = $jsprice; //结算价
				}
				$periodStart = date('Y-m-d',$order_start);
				$periodEnd = date('Y-m-d',$order_end);
				$periodPrices=<<<XML
						<periodStart>{$periodStart}</periodStart>
						<periodEnd>{$periodEnd}</periodEnd>
						<validWeek></validWeek>
						<invalidDate></invalidDate>
						<marketPrice>{$marketPrice}</marketPrice>
						<sellPrice>{$sellPrice}</sellPrice>
						<settlePrice>{$settlePrice}</settlePrice>
						<sellstock>{$sellstock}</sellstock>						
						<minimum>{$minimum}</minimum>
						<maximum>{$maximum}</maximum>
XML;
			}
		}
		else{
			//日历模式||有效期模式
			$i_startime = time(date('Y-m-d')) + ($ddays * 86400);
			$i_endtime = $i_startime + 86400 * $searchday;
			for($i=$i_startime;$i<=$i_endtime;$i+= 86400){   
				$itime = date('Y-m-d',$i);
				$getprice = $inSide->Dynamic_Price_And_Storage($ac,$pid,$itime,1,1,1,$aid);
				if($getprice == 105 || $getprice ==1065 || $getprice ==103) continue;
				$getpricexml =  simplexml_load_string($getprice);
				$lprice = (int)$getpricexml->Rec->UUsprice;  //零售价
				$sellstock = ((string)$getpricexml->Rec->UUstorage == -1) ? '9999':(string)$sellPrice_data_xml->Rec->UUstorage;	
				$maximum = $sellstock;
				if($cooperation_way == 0){ //佣金模式,获取建议零售价
					$sellPrice = $lprice;
				} 
				elseif($cooperation_way == 1){ //底价模式,获取结束价
					$getprice = $inSide->Dynamic_Price_And_Storage($ac,$pid,$itime,1,0,1,$aid);
					if($getprice == 105 || $getprice ==1065 || $getprice ==103) continue;
					$getpricexml =  simplexml_load_string($getprice);
					$jsprice = (int)$getpricexml->Rec->UUsprice;  //结算价
					$sellPrice = $lprice;  //售票价
					$settlePrice = $jsprice; //结算价
				}				
				if($sellstock !=0){ 
				$calendarPricesss=<<<XML
<calendarPrice>
<useDate>{$itime}</useDate>
<marketPrice>{$marketPrice}</marketPrice>   
<sellPrice>{$sellPrice}</sellPrice>
<settleprice>{$settlePrice}</settleprice>
<sellstock>{$sellstock}</sellstock>
<minimum>{$minimum}</minimum>
<maximum>{$maximum}</maximum>
</calendarPrice>
XML;
				$calendarPrices .= $calendarPricesss;	 
				}		 	
			}
			
		}		
		$eticketType = 'S_STRING'; //电子票类型：短信
		$smsTemplet = '您将会在3-5分钟内收到电子票，在景区售票处取票入园。';	//短信模板
		$data_array= array( //需要的参数
			'count'			=> $count,
			'resourceId'	=> (string)$tids,
			'sightName'		=> $sightName,
			'city'			=> $city,
			'sightAddress'	=> $sightAddress,
			'productName'	=> $sightName.$productName,
			'paymentType'	=> $paymentType,
			'validType'		=> $validType,
			'bookAdvanceTime'=> $bookAdvanceTime,
			'daysAfterUseDateValid'=> $daysAfterUseDateValid,
			'remind'		=> $remind,
			'smsTemplet'	=> $smsTemplet,
			'eticketType'	=> $eticketType,
			'calendarPrices'=> $calendarPrices,
			'feeInfo'		=> $feeInfo,
			'bookAdvanceDay'=> $bookAdvanceDay,
			'autoCancelTime'=> $autoCancelTime,
			'useAdvanceHour'=> $useAdvanceHour,
			'nameRequired' 	=> $nameRequired,
			'visitPersonRequiredForQuantity'=> $visitPersonRequiredForQuantity,
			'refundInfo' 	=> $refundInfo	,
			'periodPrices'	=> $periodPrices		
		);
		// print_r($data_array);exit;
		return $data_array; 
}

//获取产品body部分
function Get_Product_Body_XML($string_array,$calendarPrices=null){ //xml的body部分
$string_content =<<<XML
			<productInfo>
				<baseInfo>
					<resourceId>{$string_array['resourceId']}</resourceId>  
					<sights>
						<sight>
							<sightName>{$string_array['sightName']}</sightName> 
							<sightAddress>{$string_array['sightAddress']}</sightAddress>
							<city>{$string_array['city']}</city>
							<sightlon></sightlon>
							<sightlat></sightlat>
						</sight>
					</sights>
					<productName>{$string_array['productName']}</productName>   
				</baseInfo>
				<bookConfig>
					<paymentType>{$string_array['paymentType']}</paymentType>
					<advanceOption>
						<bookAdvanceDay>{$string_array['bookAdvanceDay']}</bookAdvanceDay>
						<bookAdvanceTime>{$string_array['bookAdvanceTime']}</bookAdvanceTime>
						<useAdvanceHour>{$string_array['useAdvanceHour']}</useAdvanceHour>
					</advanceOption>
					<autoCancelTime>{$string_array['autoCancelTime']}</autoCancelTime>
					<contactPersonRequired>
						<nameRequired>{$string_array['nameRequired']}</nameRequired>
						<namePinyinRequired></namePinyinRequired>
						<emailRequired></emailRequired>
						<addressRequired></addressRequired>
					</contactPersonRequired>
					<bookPersonType>CONTACT_PERSON</bookPersonType>
					<visitPersonRequiredForQuantity>{$string_array['visitPersonRequiredForQuantity']}</visitPersonRequiredForQuantity>
					<visitPersonRequired>
						<nameRequired>{$string_array['nameRequired']}</nameRequired>
						<namePinYinRequired></namePinYinRequired>
						<credentialsRequired></credentialsRequired>
						<credentialsRequiredTypes></credentialsRequiredTypes>
						<userRequiredDefined1></userRequiredDefined1>
						<userRequiredDefined2></userRequiredDefined2>
					</visitPersonRequired>
					<perPhoneMaximum></perPhoneMaximum>
					<perPhoneMaximumType></perPhoneMaximumType>
				</bookConfig>
				<priceConfig>
					<validType>{$string_array['validType']}</validType>
					<daysAfterUseDateValid>{$string_array['daysAfterUseDateValid']}</daysAfterUseDateValid>
					<daysAfterBookDateValid></daysAfterBookDateValid>
					<dayUseTimePeriod></dayUseTimePeriod>						
					<calendarPrices>
						{$string_array['calendarPrices']}
					</calendarPrices>
					<periodPrice>
						{$string_array['periodPrices']}
					</periodPrice>
				</priceConfig>
				<promoteConfig>
					<cashBackMoney></cashBackMoney>
				</promoteConfig>
				<productDescription>
					<feeInfo>{$string_array['feeInfo']}</feeInfo>
					<feeInclude></feeInclude>
					<feeExclude></feeExclude>
					<pickupTime></pickupTime>
					<pickupAddress></pickupAddress>
					<remind>{$string_array['remind']}</remind>
					<refundOption>
						<canRefund>TRUE</canRefund>
						<refundApplyTimeBeforeValidEndDay></refundApplyTimeBeforeValidEndDay>
						<refundChargeType>ORDER</refundChargeType>
						<refundCharge>0</refundCharge>
						<refundInfo>{$string_array['refundInfo']}</refundInfo>
					</refundOption>
				</productDescription>
				<otherConfig>
					<telephone></telephone>
					<salePeriods>
						<salePeriod>
							<saleStartTime></saleStartTime>
							<saleEndTime></saleEndTime>
						</salePeriod>
					</salePeriods>
					<smsTemplet>{$string_array['smsTemplet']}</smsTemplet>
					<eticketType>{$string_array['eticketType']}</eticketType>
				</otherConfig>
			</productInfo>
XML;
	return $string_content;
}

//产品xml的头部部分
function Get_Product_XML($string_content,$count){
	$nowdate = date('Y-m-d H:i:s');
	$string=<<<XML
<?xml version="1.0" encoding="UTF-8"?>
<response xsi:schemaLocation="http://piao.qunar.com/2013/QMenpiaoResponseSchema QMResponseDataSchema-2.0.1.xsd" xmlns="http://piao.qunar.com/2013/QMenpiaoResponseSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<header>
	<application>Qunar.Menpiao.Agent</application>
	<processor>SupplierDataExchangeProcessor</processor>
	<version>v2.0.1</version>
	<bodyType>GetProductByQunarResponseBody</bodyType>
	<createUser>SupplierSystemName</createUser>
	<createTime>$nowdate</createTime>
	<code>1000</code>
	<describe>成功</describe>
</header>
<body xsi:type="GetProductByQunarResponseBody">
	<count>$count</count>   
	<productInfos>
      $string_content
	</productInfos>
</body>
</response>
XML;
print_r($string);exit; 
	return $string;
}

//用户退款成功推送到此地址通知去哪儿 
function User_refund_notice_qunar($applyOrder_array){
	$post_data = $applyOrder_array; 
	$url='http://coop.12301.cc/callback/noticeOrderRefundApproveResult.php';
	$o=""; 
	foreach ($post_data as $k=>$v){ 
	$o.= "$k=".urlencode($v)."&"; 
	} 
	$post_data=substr($o,0,-1); 
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_POST, 1); 
	curl_setopt($ch, CURLOPT_HEADER, 0); 
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_URL,$url); 
	curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); 
	$reponse = curl_exec($ch);
	curl_close($ch);
	return $reponse;
}
?>